/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int depth(TreeNode *root)
    {
        if(root == nullptr) return 0;
        int l = depth(root->left);
        int r = depth(root->right);

        // 遍历每个节点，每次更新经过每一个节点的最长路径
        ans = max(ans, l + r);  
        
        return max(l, r) + 1;
    }
    int ans = 0;        

    int diameterOfBinaryTree(TreeNode* root) {
        depth(root);
        return ans;
    }
};